from rest_framework import serializers
from api import models
from rest_framework.exceptions import ValidationError


class RegisterSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(label='确认密码', max_length=8, write_only=True)
    password = serializers.CharField(label='密码', max_length=8, write_only=True)

    class Meta:
        model = models.UserInfo
        fields = ['username', "phone", "password", "confirm_password"]

    def validate_username(self, value):
        exists = models.UserInfo.objects.filter(username=value, deleted=False).exists()
        if exists:
            raise ValidationError("用户名已存在")
        return value

    def validate_phone(self, value):
        exists = models.UserInfo.objects.filter(phone=value, deleted=False).exists()
        if exists:
            raise ValidationError("手机号已存在")
        return value

    def validate_confirm_password(self, value):
        password = self.initial_data.get('password')
        if password == value:
            return value
        raise ValidationError("两次密码不一致")


# 登录校验  允许用户名或手机号码登录
class AuthSerializer(serializers.Serializer):
    username = serializers.CharField(label='用户名',write_only=True,required=False)
    phone = serializers.CharField(label='手机号',write_only=True,required=False)
    password = serializers.CharField(label='密码',write_only=True,min_length=8)

    def validate_username(self,value):
        # 判断是否输入用户名或手机号
        username = self.initial_data.get('username')
        phone = self.initial_data.get('phone')
        if not  username and not phone:
            raise  ValidationError('用户名或手机号为空！')
        if username and phone:
            raise ValidationError('登陆用户名只能选择一个')
        return value